﻿using CloudFranceTriple.Models;
using CloudFranceTriple.WebRole.Filters;
using CloudFranceTriple.WebRole.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;

namespace CloudFranceTriple.WebRole.Controllers
{
    [HandleError]
    public class HomeController : BaseController
    {
        private cloudfrAboq2RsDMEntities db = new cloudfrAboq2RsDMEntities();
        private UsersContext userContext = new UsersContext();

        private readonly IWebSecurityWrapper _webSecurity;
        public HomeController()
        {
            this._webSecurity = new WebSecurityWrapper();
        }

        public HomeController(IWebSecurityWrapper webSecurity)
            : base(webSecurity)
        {
            this._webSecurity = webSecurity;
        }

        [AllowAnonymous()]
        [ChildActionOnly]
        public ActionResult PollItem()
        {
            ViewBag.Topic_Id = 0;
            ViewBag.IsAuthor = User.IsInRole("RoleAuthorPollOnPortail");
            ViewBag.IsTopicAuthor = User.IsInRole("RoleAuthorPollOnPortail");

            var query = db.PollSet.Include("PollAnswerSet").Include("PollAnswerSet.PollUserSet").Where(poll => poll.ForumTopic_Id == null);
            return PartialView("_PollItem", query);
        }

        [ChildActionOnly]
        public ActionResult LastConnected(Int32 MaximumNumberOfUsersToReturn = 20)
        {
            List<String> ConnectedUsers = new List<string>();
            var members = userContext.UserProfiles.Where(ul => ul.ShowInNonAdminList).OrderByDescending(user => user.LastRequestDate).Take(MaximumNumberOfUsersToReturn);
            var durationFormat = "d' j 'h' h 'm' min'";
            foreach (CloudFranceTriple.WebRole.Models.UserProfile u in members)
            {
                ConnectedUsers.Add(String.Format("{0} {1}", u.UserName, (DateTime.UtcNow.Subtract(u.LastRequestDate)).ToString(durationFormat)));
            }
            return PartialView("_LastConnected", ConnectedUsers);
        }

        [ChildActionOnly]
        public ActionResult GetTodayBirthday()
        {
            var TodayBirthDay = new List<Birthday>();
            var members = userContext.UserProfiles.Where(ul => ul.ShowInNonAdminList);

            foreach (CloudFranceTriple.WebRole.Models.UserProfile u in members)
            {
                if (u.ShowInBirthdayList && (new DateTime(DateTime.Now.Year, u.Birthday.Month, u.Birthday.Day).Date == DateTime.UtcNow.Date))
                {
                    TodayBirthDay.Add(new Birthday() { Username = String.Format("{0} ({1} {2})", u.UserName, (DateTime.Now.Year - u.Birthday.Year).ToString(), CloudFranceTriple.WebRole.Properties.Resources.BirthdayYears) });
                }
            }
            return PartialView("_TodayBirthDay", TodayBirthDay.ToList());
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult GetNextUserBirthday(Int32 MaximumNumberOfUsersToReturn = 10)
        {
            var NextUserBirthday = new List<Birthday>();
            Int32 RemainingDays;
            var members = userContext.UserProfiles.Where(ul => ul.ShowInNonAdminList);

            foreach (CloudFranceTriple.WebRole.Models.UserProfile u in members)
            {
                if (u.ShowInBirthdayList && (new DateTime(DateTime.Now.Year, u.Birthday.Month, u.Birthday.Day).Date != DateTime.UtcNow.Date))
                {
                    RemainingDays = ((new DateTime(DateTime.Now.Year, u.Birthday.Month, u.Birthday.Day) < DateTime.Now) ? new DateTime(DateTime.Now.Year + 1, u.Birthday.Month, u.Birthday.Day) : new DateTime(DateTime.Now.Year, u.Birthday.Month, u.Birthday.Day)).Subtract(DateTime.Now).Days + 1;
                    NextUserBirthday.Add(new Birthday() { Username = String.Format("{0} {1} {2}", u.UserName, RemainingDays, CloudFranceTriple.WebRole.Properties.Resources.BirthdayDays), RemainingDays = RemainingDays });
                }
            }
            return PartialView("_NextUserBirthday", NextUserBirthday.OrderBy(birth => birth.RemainingDays).ToList());
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ForumTopicItem()
        {
            if (User.Identity.IsAuthenticated)
            {
                var catAuthor = new List<Int32>();
                foreach (Int32 catId in ForumCategoryAllowed)
                    if (UserRightLevelByCategoryId(catId, User.Identity.IsAuthenticated) >= RightLevel.Author)
                        catAuthor.Add(catId);
                ViewBag.ShowCreate = (catAuthor.Count() > 0);
            }
            else
            {
                ViewBag.ShowCreate = false;
            }
            return PartialView("_ForumTopicsItem", GetForumLastNPost(20));
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult BirthdayItem()
        {

            return PartialView("_BirthdayItem");
        }

        [AllowAnonymous]
        public ActionResult Index()
        {
            ViewBag.GravatarImageUrl = String.Format("https://www.gravatar.com/avatar/{0}?s=160&d=http://s19.postimage.org/62du01yov/default_avatar_82.png&r=g", base.UserGravatarHash);
            ViewBag.GravatarImageAlt = User.Identity.Name;
            // Afficher la vue
            return View();
        }

        [AllowAnonymous]
        public ActionResult About()
        {
            return View();
        }

        [AllowAnonymous]
        public ActionResult Contact()
        {
            return View();
        }
    }
}
